package com.pay.alipay.controller;

import com.alipay.api.AlipayApiException;
import com.pay.alipay.pojo.Order;
import com.pay.alipay.service.AlipayService;
import com.pay.alipay.service.OrderService;
import com.pay.alipay.utils.SysConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
@Slf4j
public class AliPayController {

    @Autowired
    private AlipayService service;

    @Autowired
    OrderService orderService;
    /**
     * 支付方法
     */
    @RequestMapping("/trade")
    public void alipay(HttpServletResponse response) throws IOException {
      String trade=service.createTrade();
      response.setContentType("text/html;charset=utf-8");
      response.getWriter().println(trade);
    }

    /**
     * 异步通知
     */

    @PostMapping("/trade/notify")
    public String tradeNotify(@RequestParam Map<String,String> params) throws AlipayApiException {
        log.info("开始处理异步通知请求");
        //1.验证证书上的公钥是否一直
        boolean signVerified=service.aliSignature(params);
         if(!signVerified){
             log.info("验证失败");
             return "验签失败";
         }
        System.out.println(1);
         //2.商户发送的订单号是否一致
        String out_trade_no=params.get("out_trade_no");
        Order order= orderService.getByTradeNo(out_trade_no);
        System.out.println(order);
         if(order==null){
             log.info("订单不存在");
             return "订单不存在fail";
         }
        System.out.println(2);
         //3.验证金额是否一致
         String total_amount=params.get("total_amount");
         System.out.println("支付宝返回的金额为："+total_amount);
         Double parseDouble=Double.parseDouble(total_amount);
         System.out.println(parseDouble);
         Double totalAmount=Double.parseDouble(order.getTotalAmount());
        System.out.println("数据库订单金额："+totalAmount);
         if(!parseDouble.equals(totalAmount)){
             log.info("验证失败，金额不一致");
             return "失败，金额不一致";
         }
        System.out.println(3);
         //4.验证状态是否一致
        String trade_status=params.get("trade_status");
         if(!SysConstant.TRADE_SUCCESS.equals(trade_status)){
             log.info("验证失败，交易状态不一致");
         }
        System.out.println(4);
         //5.修改订单状态
        orderService.updateOrderStatus(order,SysConstant.TRADE_SUCCESS);
        System.out.println("修改订单状态成功");
        return "success";
    }
}
